define('AttachmentNew', function () {

  var qiniu_public_url = "http://ohqm88vkq.bkt.clouddn.com/";
  var qiniu_private_url = "http://ohqmxaqtq.bkt.clouddn.com/";
  var attachment_server_url = "http://a8-domain.pagoda.com.cn:20101";
  var React = require("react");
  var ReactDOM = require("react-dom");

  var _AttachmentMgt = React.createClass({
    dataChanged: false,
    uploader: null,
    pickfiles: "undefined",
    getDefaultProps: function () {
      return {
        allowMultiple: true,
        imgClass: "common-img",
        bucketname: 'public',
        addButtonSrc: 'images/uploadPic.png',
      };
    },
    getInitialState: function () {
      return {
        files: [],
        networkFail: false
      }
    },
    save: function () {
      var res = [];
      $.each(this.state.files, function (idx, item) {
        if (item.deleted) {
          //todo: delete the file
        } else {
          res.push(item.fileKey);
        }
      });
      this.props.allowMultiple;
      this.props.callbackParent(res);
      return res;
    },
    addFileToList: function (file) {
      var myself = this;
      var param = {
        fileKey: file,
      };
      var files = myself.state.files;
      if (!this.props.allowMultiple) {
        files = [];
      }
      files.push(param);
      this.dataChanged = true;
      myself.setState({files: files});
    },
    changeFileInList: function (file) {//变更文件在交互上很难做好，暂时屏蔽这个功能
      /*if(this.curSelected != -1){
       var files = this.state.files;
       files[this.curSelected].fileKey = file;//todo, 需要删除老的资源
       }
       this.dataChanged = true;
       this.setState({files:files});
       this.curSelected = -1;*/
    },
    handleImgClick: function (evt) {
      var r = confirm("需要删除该图片吗", "提示");
      if (r == true) {
        var files = this.state.files;
        if (evt.target.id < files.length) {
          files[evt.target.id].deleted = true;
        }
        this.dataChanged = true;
        this.setState({files: files});
      }
    },
    getTokenMessage: function () {
      var dfd = $.Deferred();
      $.post({
        url: attachment_server_url + '/fileMgr/qiniu/getUpToken',
        async: false,
        data: JSON.stringify({
          bucketname: this.props.bucketname
        }),
        contentType: 'application/json',
        dataType: 'json',
        success: function (data) {
          dfd.resolve(data.data);
        },
        error: function () {
          dfd.reject();
        }
      });
      return dfd;
    },
    componentWillMount: function () {
      this.pickfiles = "uid" + Math.random();
    },
    componentDidMount: function () {
      var myself = this;
      //取得token后初始化qiniu
      var domain = qiniu_public_url;
      if (this.props.bucketname == 'private') domain = qiniu_private_url;
      this.getTokenMessage().done(function (token) {
        //引入Plupload 、qiniu.js后
        myself.uploader = Qiniu.uploader({
          runtimes: 'html5,flash,html4',      // 上传模式，依次退化
          browse_button: myself.pickfiles,         // 上传选择的点选按钮，必需
          uptoken: token,
          get_new_uptoken: false,             // 设置上传文件的时候是否每次都重新获取新的uptoken
          domain: domain,     // bucket域名，下载资源时用到，必需
          //container: 'container',             // 上传区域DOM ID，默认是browser_button的父元素
          max_file_size: '100mb',             // 最大文件体积限制
          flash_swf_url: 'path/of/plupload/Moxie.swf',  //引入flash，相对路径
          max_retries: 3,                     // 上传失败最大重试次数
          //dragdrop: true,                     // 开启可拖曳上传
          //drop_element: 'container',          // 拖曳上传区域元素的ID，拖曳文件或文件夹后可触发上传
          chunk_size: '4mb',                  // 分块上传时，每块的体积
          auto_start: true,                   // 选择文件后自动上传，若关闭需要自己绑定事件触发上传,
          scope: "bucket",
          unique_names: true,
          log_level: 6,
          init: {
            'FilesAdded': function (up, files) {
              plupload.each(files, function (file) {
                // 文件添加进队列后，处理相关的事情
              });
            },
            'BeforeUpload': function (up, file) {
              // 每个文件上传前，处理相关的事情
            },
            'UploadProgress': function (up, file) {
              // 每个文件上传时，处理相关的事情
            },
            'FileUploaded': function (up, file, info) {
              var res = JSON.parse(info);
              if (res != null) {
                myself.addFileToList(res.key);
              }
            },
            'Error': function (up, err, errTip) {
              //上传出错时，处理相关的事情
            },
            'UploadComplete': function (evt, uploadedFiles) {
              //队列文件处理完毕后，处理相关的事情
            },
            'Key': function (up, file) {
              // 若想在前端对每个文件的key进行个性化处理，可以配置该函数
              // 该配置必须要在unique_names: false，save_key: false时才生效
            }
          }
        });
      }).fail(function () {
        myself.setState({networkFail: true});
      });
    },
    render(){
      var files = [];
      var addButtonClass = this.state.networkFail ? "network-fail" : "";
      var addButtonImg = this.props.addButtonSrc;
      {
        var myself = this;
        if (this.props.allowMultiple) {
          $.each(this.state.files, function (idx, item) {
            if (!item.hasOwnProperty('deleted')) {
              var url = Qiniu.imageView2({
                mode: 3,  // 缩略模式，共6种[0-5]
                w: 100,   // 具体含义由缩略模式决定
                h: 100,   // 具体含义由缩略模式决定
                q: 100,   // 新图的图像质量，取值范围：1-100
                format: 'png'  // 新图的输出格式，取值范围：jpg，gif，png，webp等
              }, item.fileKey);
              if (this.props.bucketname == 'private') {
                //获取七牛下载令牌
                $.post({
                  url: attachment_server_url + '/fileMgr/qiniu/getDownUrl',
                  async: false,
                  data: JSON.stringify({
                    bucketname: this.props.bucketname,
                    fileKey: item.fileKey
                  }),
                  contentType: 'application/json',
                  dataType: 'json',
                  success: function (data) {
                    url = data.data;
                  },
                });
              }
              files.push(<img id={idx} key={idx} className={myself.props.imgClass} src={url} onClick={myself.handleImgClick}/>)
            }
          });
        } else {
          if (this.state.files.length > 0) {

            if (this.props.bucketname == 'private') {
              //获取七牛下载令牌
              $.post({
                url: attachment_server_url + '/fileMgr/qiniu/getDownUrl',
                async: false,
                data: JSON.stringify({
                  bucketname: this.props.bucketname,
                  fileKey: this.state.files[0].fileKey
                }),
                contentType: 'application/json',
                dataType: 'json',
                success: function (data) {
                  addButtonImg = data.data;
                },
              });
            } else {
              addButtonImg = qiniu_public_url + "/" + this.state.files[0].fileKey;
            }
          }
        }
        this.save();
      }
      return (
        <div>
          {files}
          <div id='container'>
            <img id={this.pickfiles} style={{height:'100px',width:'100px'}} className={addButtonClass} src={addButtonImg}/>
          </div>
        </div>
      );
    }
  });
  return _AttachmentMgt;
});
